/**
 * Created by ecervetti on 01/03/14.
 */
var GameIhm = function (DivContenerId) {
    var thisIHM = this ;
    thisIHM.graphics = new Graphics(document.getElementById(DivContenerId)) ;
    var ratio = 1.775 ;
    if( thisIHM.graphics.height >= thisIHM.graphics.width) {
        //Ecran en mode page
        //la reso horizontable va fixer la taille des cases.
        thisIHM.caseWidth = Math.floor(thisIHM.graphics.width/thisIHM.discrWidth) ;
        thisIHM.discrHeight = Math.floor(thisIHM.graphics.height/thisIHM.discrWidth ) ;
    } else {
        //Ecran en mode portrait
        thisIHM.caseWidth = Math.floor((thisIHM.graphics.height/ratio )/thisIHM.discrWidth) ;
    }
    thisIHM.discrHeight = Math.floor(thisIHM.graphics.height/thisIHM.caseWidth ) ;
    thisIHM.decaY = thisIHM.graphics.height - thisIHM.discrHeight*thisIHM.caseWidth ;
    thisIHM.decaX = (thisIHM.graphics.width - thisIHM.discrWidth*thisIHM.caseWidth)/2 ;
    thisIHM.graphics.addFrame("main",1);
    thisIHM.startTme =  new Date().getTime() ;
    thisIHM.graphics.addFrame("decor",-1);
    thisIHM.graphics.addFrame("fond",-2);
    thisIHM.graphics.drawGradientTwoColors(
        "fond",
        thisIHM.decaX,
        0,
        thisIHM.graphics.width-thisIHM.decaX,
        thisIHM.graphics.height,
        "#C1F0F6",
        "#A893CB"
    );
    var foreground = thisIHM.graphics.addFrame("foreground",10);
    thisIHM.graphics.vignette("foreground",thisIHM.decaX,thisIHM.graphics.width-2*thisIHM.decaX);
    foreground.addEventListener('mousedown', function(event) {
        var x = event.x;
        if(!x ) x = event.clientX ;
        x -= foreground.offsetLeft ;
        thisIHM.handleClick(x);
    });
    thisIHM.univers = new Univers(thisIHM);
    thisIHM.decor3X = thisIHM.decaX ;
    thisIHM.loadRessources();
    thisIHM.reset();
    thisIHM.start();
    thisIHM.loadPersonalBestScore();
    thisIHM.setBestScore();
    setTimeout(function(){
        thisIHM.whenReady(function(){
            thisIHM.messageStart();
        });
    },3)

};


GameIhm.prototype =  {
    lastDisplayTime : null ,
    decaSpriteX:0 ,//Le décalage en cours de jeu du premier bloc en bas à gauche
    decaSpriteY:0 ,
    decaY: 0 , //le décalage du haut et du bas suite à l'adaptation à l'écran, pour que le plancher soit bien en bas
    decaX : 0 ,
    decorX : 200 ,
    decorY : 200 ,
    decor2X : 800 ,
    decor2Y : -200 ,
    decor3X : 0 ,
    decor3Y : 0 ,
    /**
     * @type {Graphics}
     */
    graphics : null ,

    duckAnimationStep : 0 ,
    discrWidth : 10 ,
    discrHeight : 8 ,
    paused : false ,
    bpm : 140 ,
    startTme : 0 ,
    pauseSetTime : false , //pour mettre un timeout sur le readonly de la pause
    animation : false , //une animation en cours empeche le clic
    bestscore : null,
    bestpersonalscore : null,
    bestauthor: null,
    /**
     * @type {Univers}
     */
    univers: null,
    ready : false ,
    /**
     * @type {Sprite[]}
     */
    tabSprites : [] ,
    generiqueAudio :null ,
    indexSpriteCloud1 : 7 ,
    indexSpriteCloud2 : 7 ,

    loadRessources : function() {
        var thisIHM = this ;
        var loadImage = function(i,src,resizew,resizeh) {
            thisIHM.tabSprites[i]= new Sprite(src,resizew,resizeh) ;
        };
        loadImage(0,'mountainduck.png',0,0);
        loadImage(1,'case1.png',thisIHM.caseWidth,thisIHM.caseWidth);
        loadImage(2,'case2.png',thisIHM.caseWidth,thisIHM.caseWidth);
        loadImage(3,'credits1.png',0,0);
        loadImage(4,'credits2.png',0,0);
        loadImage(5,'duck_1.png',thisIHM.caseWidth,thisIHM.caseWidth);
        loadImage(6,'duck_2.png',thisIHM.caseWidth,thisIHM.caseWidth);
        loadImage(7,'cloud.png',0,0);
        loadImage(8,'mountain.png',0,0);
        loadImage(9,'cloud2.png',0,0);
        loadImage(10,'cloud3.png',0,0);
        loadImage(11,'cloud4.png',0,0);

        thisIHM.generiqueAudio = new Audio("ducktheme.mp3");
        thisIHM.generiqueAudio.loop = true ;
    },

    isReady : function() {
        var thisIHM = this ;
        var res = true ;
        for(var i = 0 ; i < thisIHM.tabSprites.length ; i++ ) {
            res = res && thisIHM.tabSprites[i].ready ;
        }
        return res ;
    },

    whenReady : function(f) {
        var thisIHM = this ;
        if( ! thisIHM.isReady()) {
            setTimeout(function(){
                thisIHM.whenReady(f);
            },10);
            return ;
        }
        f();
    },

    start: function() {
        var thisIHM = this ;
        thisIHM.whenReady(function(){
            setTimeout(function(){
                thisIHM.update();
            },200);
        });
    },

    drawCanard : function() {
        var thisIHM = this ;
        var thisUnivers = thisIHM.univers ;
        thisIHM.duckAnimationStep = ( thisIHM.duckAnimationStep +1 ) % 2 ;
        thisIHM.displaySpriteFromUniversCoord(thisUnivers.duck.i,thisUnivers.duck.j,5+thisIHM.duckAnimationStep);
    },


    reset: function() {
        var thisIHM = this ;
        thisIHM.decaSpriteX = 0 ;
        thisIHM.decaSpriteY = 0 ;
    },

    redraw : function() {
        var thisIHM = this ;
        var thisUnivers = thisIHM.univers ;


        //On enleve le surplus en haut qui n'est pas rafraichi, avant l'affichage du canard et de la courbe
        thisIHM.graphics.clearRect("main",thisIHM.decaX,0,thisIHM.graphics.width-thisIHM.decaX,thisIHM.decaY);

        thisIHM.basicLooper(function(i,j){

            var iUnivers = thisIHM.getUniversIFromDiscrI(i) ;
            var jUnivers = thisIHM.getUniversJFromDiscrJ(j) ;
            thisIHM.displaySpriteFromUniversCoord(iUnivers,jUnivers,thisUnivers.spriteInfoProvider(iUnivers,jUnivers));
        });



        thisIHM.graphics.drawText("main",Math.floor(thisIHM.univers.jPointerIHM)+" ft",thisIHM.decaX+20,100,"36px Arial","yellow","black",1,1);

        var tutoCoeff  = ((20-thisIHM.univers.jPointerIHM)/20)*(1+thisIHM.getPhase())/4;
        if(tutoCoeff > 0 && thisUnivers.selectedCol != thisUnivers.duck.trajectoire.toI ) {

            //Trajectoire
            var destX =  thisIHM.getCanvasXFromGameI(thisUnivers.duck.trajectoire.toI);
            var destY =  thisIHM.getCanvasYFromGameJ(thisUnivers.duck.trajectoire.toJ-1);
            var controlPoint = thisUnivers.duck.trajectoire.getControlPoint() ;
            var gradient = thisIHM.graphics.getGradientTwoColors("main",
                thisIHM.decaX,
                0,
                thisIHM.graphics.width-thisIHM.decaX,
                thisIHM.graphics.height,
                "yellow",
                "white") ;
            thisIHM.graphics.drawQuadratic(
                "main",
                thisIHM.getCanvasXFromGameI(thisUnivers.duck.trajectoire.originI+0.5),
                thisIHM.getCanvasYFromGameJ(thisUnivers.duck.trajectoire.originJ-1)-4,
                thisIHM.getCanvasXFromGameI(controlPoint.x+0.5),
                thisIHM.getCanvasYFromGameJ(controlPoint.y-1)-4,
                thisIHM.getCanvasXFromGameI(thisUnivers.duck.trajectoire.toI+0.5),
                thisIHM.getCanvasYFromGameJ(thisUnivers.duck.trajectoire.toJ-1)-4,
                null,
                gradient,
                3,
                tutoCoeff
            );
            var font =  Math.round(thisIHM.graphics.width/120)+"px Arial";
            thisIHM.graphics.drawText("main","CLICK",destX+thisIHM.caseWidth/10,destY- thisIHM.caseWidth/10,font,"yellow",
                "black",1,tutoCoeff);
            thisIHM.graphics.drawRect("main",2+destX,
                2+destY,
                thisIHM.caseWidth-4,
                thisIHM.graphics.height,gradient,"black",1,tutoCoeff);
        }

        var oldx = 0 ;
        var oldy = 0 ;
        //Halo de bord
        var tabCoords = [] ;
        for(var i=0;i<=thisIHM.discrWidth;i++) {
            var iAbs = thisIHM.getUniversIFromDiscrI(i);
            var j = thisIHM.univers.data[Math.floor(iAbs)].height ;
            var x = thisIHM.getCanvasXFromGameI(iAbs);
            var y = thisIHM.getCanvasYFromGameJ(j);
            if(i==0) {
                tabCoords.push(new Coords(x,y));
            } else {
                tabCoords.push(new Coords(oldx+thisIHM.caseWidth,oldy));
                tabCoords.push(new Coords(x,y));
            }
            oldx = x ;
            oldy = y ;
        }
        thisIHM.graphics.drawSegments("main",tabCoords,"","#B2B8DC",thisIHM.caseWidth/8,0.2);
        thisIHM.graphics.drawSegments("main",tabCoords,"","#B2B8DC",thisIHM.caseWidth/5,0.2);


        thisIHM.drawCanard();


        //thisIHM.graphics.clearRect("main",thisIHM.graphics.width-thisIHM.decaX,0,thisIHM.caseWidth,thisIHM.graphics.height);

        //thisIHM.graphics.clearRect("main",thisIHM.decaX-thisIHM.caseWidth,0,thisIHM.caseWidth,thisIHM.graphics.height);


        //Le fond est rafraichi en assynchrone
        setTimeout(function(){
            //On vire tout
            thisIHM.graphics.clearRect("decor",thisIHM.decaX,0,thisIHM.graphics.width-2*thisIHM.decaX,thisIHM.graphics.height );
            var phase = thisIHM.getPhaseMesure() ;
            var scaling1 = 0.9 + 0.1*phase ;
            var scaling2 = 0.9 + 0.1*phase ;
            thisIHM.decorX-=0.5;
            thisIHM.decorY+=0.25;

            var getIdSpriteNuage = function() {
                if( thisUnivers.jPointerIHM > 200 )
                    return 11 ;
                if( thisUnivers.jPointerIHM > 100 )
                    return 10 ;
                if( thisUnivers.jPointerIHM > 50 )
                    return 9 ;
                return 7 ;
            };

            if( thisIHM.decorX < ( thisIHM.decaX/2 -  800) || thisIHM.decorY > thisIHM.graphics.height) {
                thisIHM.decorX = thisIHM.graphics.width - thisIHM.decaX/2;
                thisIHM.decorY = -300 ;
                thisIHM.indexSpriteCloud1 = getIdSpriteNuage();

            }
            var montagneH = thisIHM.graphics.height/2 ;
            var montagneW =  (thisIHM.graphics.height/2)*700/300;
            thisIHM.decor3Y = thisIHM.graphics.height - montagneH ;
            thisIHM.graphics.drawImage("decor",thisIHM.tabSprites[thisIHM.indexSpriteCloud1].canvas,thisIHM.decorX+300*(1-scaling1),thisIHM.decorY+150*(1-scaling1),600*scaling1,300*scaling1);
            thisIHM.decor2X-=0.5;
            thisIHM.decor2Y+=0.25;
            if( thisIHM.decor2X < ( thisIHM.decaX/2 -  800)|| thisIHM.decor2Y > thisIHM.graphics.height) {
                thisIHM.decor2X = thisIHM.graphics.width - thisIHM.decaX/2;
                thisIHM.decor2Y = -300 ;
                thisIHM.indexSpriteCloud2 = getIdSpriteNuage();
            }

            thisIHM.graphics.drawImage("decor",thisIHM.tabSprites[thisIHM.indexSpriteCloud2].canvas,thisIHM.decor2X+300*(1-scaling2),thisIHM.decor2Y+150*(1-scaling2),Math.round(600*scaling2),Math.round(300*scaling2) );
            //montagne

            thisIHM.decor3X-=0.1;

            if(thisIHM.decor3X< ( (thisIHM.decaSpriteX/2) - montagneW  ) ) {
                thisIHM.decor3X+=montagneW ;
            }
            thisIHM.graphics.drawImage("decor",thisIHM.tabSprites[8].canvas,
                thisIHM.decor3X,
                thisIHM.decor3Y,
                montagneW,
                montagneH
            );

            thisIHM.graphics.drawImage("decor",thisIHM.tabSprites[8].canvas,
                montagneW+thisIHM.decor3X,
                thisIHM.decor3Y,
                montagneW,
                montagneH
            );

        },1);
    },

    getPhase : function() {
        var thisIHM = this ;
        var tempsPasseJeu = (new Date().getTime() -  thisIHM.startTme ) ;
        var noire = 2000*60/thisIHM.bpm ;
        var ret = (tempsPasseJeu - noire*Math.floor(tempsPasseJeu/noire))/noire ;
        return Math.cos(2*Math.PI*ret) ;
    },

    getPhaseMesure : function() {
        var thisIHM = this ;
        var tempsPasseJeu = (new Date().getTime() -  thisIHM.startTme ) ;
        var noire = 8*1000*60/thisIHM.bpm ;
        var ret = (tempsPasseJeu - noire*Math.floor(tempsPasseJeu/noire))/noire ;
        return Math.cos(2*Math.PI*ret) ;
    },


    displaySpriteFromUniversCoord : function(i,j,indexSprite) {
        var thisIHM = this ;
        var x = thisIHM.getCanvasXFromGameI(i);
        var y = thisIHM.getCanvasYFromGameJ(j);
        if(indexSprite == 0) {
            thisIHM.graphics.clearRect('main',x,y,thisIHM.caseWidth,thisIHM.caseWidth );
        } else {
            thisIHM.graphics.drawImage('main',thisIHM.tabSprites[indexSprite].canvas,x, y,thisIHM.caseWidth,thisIHM.caseWidth );
            if( indexSprite == 1 ||  indexSprite == 2 ) {
                var uniq = ((i*2203+j*2833)%7)/7 ;
                var phase = thisIHM.getPhase()*uniq ;
                var x1 = -0.2*phase ;
                var y1 = -0.2*phase ;
                var x_center = x+thisIHM.caseWidth/2 ;
                var y_center = y+thisIHM.caseWidth/2 ;
                var color = "yellow" ;

                if( thisIHM.univers.jPointerIHM > 50 )
                    color = "orange" ;
                if( thisIHM.univers.jPointerIHM > 100 )
                    color = "white" ;
                if( thisIHM.univers.jPointerIHM > 200 )
                    color = "red" ;
                if( thisIHM.univers.jPointerIHM > 500 )
                    color = "blue" ;
                if( thisIHM.univers.jPointerIHM > 1000 )
                    color = "black" ;
                if( indexSprite == 1 ) {
                    var lineWidth = thisIHM.caseWidth/5 ;
                    thisIHM.graphics.drawRect(
                        'main',
                        x_center+x1*thisIHM.caseWidth,
                        y_center+y1*thisIHM.caseWidth,
                        0.4*phase*thisIHM.caseWidth,0.4*phase*thisIHM.caseWidth,color,"#39393c",lineWidth,0.7);
                    //Effet mirroir
                    var sx = ( 3*(thisIHM.caseWidth - thisIHM.caseWidth * (x/thisIHM.graphics.width))) % thisIHM.caseWidth;
                    if( (x+sx-lineWidth/2) > ( x_center+thisIHM.caseWidth*x1-lineWidth/2) &&   (x+sx)< ( x_center-thisIHM.caseWidth*x1+lineWidth/2) ){
                        thisIHM.graphics.drawRect(
                            'main',
                            x+sx,
                            Math.min(y_center+thisIHM.caseWidth*y1-lineWidth,y_center-lineWidth),
                            1,thisIHM.caseWidth*0.4*phase+lineWidth ,"white","",0,0.4);
                    }
                }
            }
        }
    },


    basicLooper: function(closCall)  {
        var thisIHM = this ;
        for(var i=0;i<=thisIHM.discrWidth;i++) {
            for(var j=0;j<=thisIHM.discrHeight;j++) {
                closCall(i,j);
            }
        }
    },



    update: function() {


        var thisIHM = this ;

        if(thisIHM.paused) {
            return ;
        }
        var thisUnivers = thisIHM.univers ;
        var translationCamera = new Coords(0,0) ;
        var timeIntervall = 0 ;
        if(!thisIHM.lastDisplayTime ) {
            thisIHM.lastDisplayTime =  new Date().getTime();
        } else {
            var newDisplayTime = new Date().getTime() ;
            timeIntervall = newDisplayTime - thisIHM.lastDisplayTime ;
            thisIHM.lastDisplayTime = newDisplayTime ;
            translationCamera = thisUnivers.physics(timeIntervall);
        }

        if(thisIHM.paused) { //Le jeu peut avoir été mis en pause apres physique
            return ;
        }

        thisIHM.decaSpriteX-=translationCamera.x*thisIHM.caseWidth ; //negatif
        thisIHM.decaSpriteY+=translationCamera.y*thisIHM.caseWidth ; //positif

        var isRecadrage = false ;

        while( thisIHM.decaSpriteX < -thisIHM.caseWidth ) {
            thisIHM.decaSpriteX+=thisIHM.caseWidth;
            isRecadrage = true ;
       }

        while( thisIHM.decaSpriteY > thisIHM.caseWidth ) {
            isRecadrage = true ;
            thisIHM.decaSpriteY=thisIHM.decaSpriteY-thisIHM.caseWidth;
        }
        thisIHM.redraw();

        setTimeout(function(){thisIHM.update()},1) ;
    },


    handleClick : function(x) {
        var thisIHM = this ;
        if(thisIHM.animation )
            return ;

        if(thisIHM.paused) {

            if( (new Date().getTime() - thisIHM.pauseSetTime) < 500 ) {
                return ;
            }
            var pf = document.getElementById("publishFb") ;
            if(pf)
                thisIHM.graphics.contenerEle.removeChild(pf);


            thisIHM.generiqueAudio.play();

            thisIHM.paused = false ;

            thisIHM.lastDisplayTime = false ;
            thisIHM.update();
            return ;
        }
        var Ui  =  thisIHM.getGameIFromCanvasX(x);
        thisIHM.univers.changeCol(Math.floor(Ui));
    },

    getGameIFromCanvasX : function(x) {
        var thisIHM = this ;
        return (x-(thisIHM.decaX))/thisIHM.caseWidth + thisIHM.univers.iPointerIHM ;
    },
/*
    getGameJFromCanvasY : function(y) {
        var thisIHM = this ;
       return (thisIHM.graphics.height - y )/thisIHM.caseWidth + thisIHM.univers.jPointerIHM ;
    },
*/
    getCanvasXFromGameI : function(i) {
        var thisIHM = this ;
        return thisIHM.decaX+(i-thisIHM.univers.iPointerIHM)*thisIHM.caseWidth ;
    },

    getCanvasYFromGameJ : function(j) {
        var thisIHM = this ;
        return  thisIHM.decaY+thisIHM.caseWidth * (thisIHM.discrHeight - 1  )
            - (j-thisIHM.univers.jPointerIHM)*thisIHM.caseWidth ;
    },

    getUniversIFromDiscrI : function(i) {
        var thisIHM = this ;
        var res = thisIHM.univers.iPointerIHM + i + thisIHM.decaSpriteX/thisIHM.caseWidth ;
        //Problemes constatés de passage avant l'unité, float javascripts horribles
        return Math.round(res*1000)/1000 ;
    },

    getUniversJFromDiscrJ : function(j) {
        var thisIHM = this ;
        var res = thisIHM.univers.jPointerIHM + j - thisIHM.decaSpriteY/thisIHM.caseWidth ;
        //Problemes constatés de passage avant l'unité, float javascripts horribles
        return Math.round(res*1000)/1000 ;
    },



    alerteNiveau : function() {
        var audio = new Audio('bell.mp3');
        audio.play();
    },



    messageStart : function() {
        var thisIHM = this ;
        thisIHM.paused = true ;
        thisIHM.pauseSetTime = new Date().getTime() ;
        var x = Math.floor((thisIHM.graphics.width-300)/2);
        var y = Math.floor((thisIHM.graphics.height-547)/2);
        thisIHM.graphics.drawImage("main",thisIHM.tabSprites[0].image,x, y,thisIHM.tabSprites[0].image.width,thisIHM.tabSprites[0].image.height);
        thisIHM.graphics.drawImage("main",thisIHM.tabSprites[3].image,x, y+300,thisIHM.tabSprites[3].image.width,thisIHM.tabSprites[3].image.height);
    },

    loadPersonalBestScore : function() {
        var name =  "bestscore=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++)
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) {
                this.bestpersonalscore = c.substring(name.length,c.length);
                return ;
            }
        }
        this.bestpersonalscore = 0 ;
    },

    setPersonalBestScore : function() {
        var d = new Date();
        d.setTime(d.getTime()+(1000*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie ="bestscore=" + this.bestpersonalscore + "; " + expires;
    },

    setBestScore : function() {
        this.sendScore("a","0");
    },


    sendScore : function(author,score) {
        var thisIHM = this ;
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4) {
                var data  = xmlhttp.responseText.split(':');
                thisIHM.bestauthor = data[0];
                thisIHM.bestscore  = data[1];
            }

        };
        xmlhttp.open("GET","score.php?author=" + author+"&score="+score+"&rand="+Math.random(),true);
        xmlhttp.send();
    },


    messageEnd : function(score) {
        var thisIHM = this ;
        if (score > thisIHM.bestpersonalscore)  {
            alert(score+" : it's your own record !");
            thisIHM.bestpersonalscore = score ;
            thisIHM.setPersonalBestScore();
        }
        if(score > thisIHM.bestscore) {
            thisIHM.bestauthor = prompt(score+" : it's the world record ! Who are you ?");
            thisIHM.bestscore = score ;
            thisIHM.sendScore(thisIHM.bestauthor,thisIHM.bestscore);
        }


        thisIHM.generiqueAudio.pause();
        thisIHM.generiqueAudio.currentTime = 0;
        thisIHM.paused = true ;
        thisIHM.pauseSetTime = new Date().getTime() ;

        var x = Math.floor((thisIHM.graphics.width-300)/2);
        var y = Math.floor((thisIHM.graphics.height-300)/2);

        thisIHM.graphics.drawImage("main",thisIHM.tabSprites[4].image,x, y,thisIHM.tabSprites[4].image.width,thisIHM.tabSprites[4].image.height);

        thisIHM.graphics.drawText("main",score,x+190,y+74,"25px Arial bold","white","black",0,1);
        thisIHM.graphics.drawText("main",thisIHM.bestpersonalscore,x+190,y+120,"25px Arial","white","black",0,1);
        thisIHM.graphics.drawText("main",thisIHM.bestscore,x+190,y+164,"25px Arial","white","black",0,1);
        thisIHM.graphics.drawText("main",thisIHM.bestauthor,x+190,y+200,"18px Arial","white","black",0,1);
        //https://developers.facebook.com/docs/ios/ui-controls#sharedialog
        //https://developers.facebook.com/docs/android/share
        var fbEle = document.createElement("div");
        fbEle.id="publishFb";
        fbEle.style.left = x+84+"px" ;
        fbEle.style.top = y+235+"px" ;
        fbEle.style.width="120px";
        fbEle.style.height="15px";
        fbEle.style.position = "absolute";
        fbEle.style.zIndex = 100 ;
        fbEle.class = "fb-share-button" ;
        fbEle.dataHref="http://gracefulstorms.com/mountainduck/" ;
        fbEle.dataWidth="120" ;
        fbEle.dataType="icon_link" ;
        thisIHM.graphics.contenerEle.appendChild(fbEle);
    }









};

document['game'] = GameIhm ;